package operation.modules.workReport.controller;

import operation.modules.workReport.entity.WorkDateEntity;
import operation.modules.workReport.entity.WorkTaskEntity;
import operation.modules.workReport.service.WorkDateService;
import operation.modules.workReport.service.WorkTaskService;
import operation.util.ReqResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 任务 控制层
*/
@RestController
@RequestMapping("api/work/task")
public class WorkTaskController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WorkTaskService workTaskService;
    @Autowired
    private WorkDateService workDateService;
    /**
     * 查询所有
     */
    @RequestMapping("/query-all")
    public ReqResult queryAll() {
        logger.info("任务表 查询所有数据");
        List<WorkTaskEntity> list = workTaskService.queryAll();
        return ReqResult.ok().put("list", list);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public ReqResult save(@RequestBody WorkTaskEntity workTaskEntity) {
        logger.info("任务表 保存信息");

        if (workTaskEntity.getTitle().equals("添加任务信息")) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = format.format(new Date());
            String dateCode = "D" + nowTime.substring(0,4) + nowTime.substring(5,7) + nowTime.substring(8,10);
            WorkDateEntity workDateEntity = workDateService.queryByCode(dateCode);
            if (workDateEntity == null) {
                return ReqResult.error(00, "没有当前日期信息");
            }
            workTaskEntity.setWorkDateId(workDateEntity.getId());
            workTaskEntity.setCreateTime(new Date());
            workTaskEntity.setTime(0);
            workTaskEntity.setStartTime(new Date());
            workTaskService.save(workTaskEntity);
        } else {
            workTaskService.updateById(workTaskEntity);
        }
        return ReqResult.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public ReqResult delete(@RequestBody Map<String, Object> params) {
        logger.info("任务表 根据id删除");
        int id = (Integer) params.get("id");
        workTaskService.removeById(id);
        return ReqResult.ok();
    }
}